package com.example.letswalk.service.serviceimpl;

import com.example.letswalk.dao.SysMenuRoleMapper;
import com.example.letswalk.pojo.Role;
import com.example.letswalk.pojo.SysMenuRole;
import com.example.letswalk.pojo.example.SysMenuRoleExample;
import com.example.letswalk.service.SysMenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysMenuRoleServiceImpl implements SysMenuRoleService{

    @Autowired
    SysMenuRoleMapper sysMenuRoleMapper;

    /***
     * 通过Role,MenuId 设置Menu
     * @param role
     * @param SysMenuIds
     */
    @Override
    public void setSysMenu(Role role, int[] SysMenuIds) {
        //删除当前角色所有的权限
        SysMenuRoleExample example= new SysMenuRoleExample();
        example.createCriteria().andRoleIdEqualTo(role.getRoleId().intValue());
        List<SysMenuRole> rps= sysMenuRoleMapper.selectByExample(example);
        for (SysMenuRole sysMenuRole : rps)
            sysMenuRoleMapper.deleteByPrimaryKey(sysMenuRole.getId());

        //设置新的权限关系
        if(null!=SysMenuIds)
            for (int mid : SysMenuIds) {
                SysMenuRole sysMenuRole = new SysMenuRole();
                sysMenuRole.setMenuId(mid);
                sysMenuRole.setRoleId(role.getRoleId().intValue());
                sysMenuRoleMapper.insert(sysMenuRole);
            }
    }

    /**
     * 通过RoleId删除Menu 删除角色的权限
     * @param roleId
     */
    @Override
    public void deleteByRole(long roleId) {
        SysMenuRoleExample example= new SysMenuRoleExample();
        int roleid = (int)roleId;
        example.createCriteria().andRoleIdEqualTo(roleid);
        List<SysMenuRole> rps= sysMenuRoleMapper.selectByExample(example);
        for (SysMenuRole sysMenuRole : rps)
            sysMenuRoleMapper.deleteByPrimaryKey(sysMenuRole.getId());

    }

    /**
     * 通过MenuId删除Role 删除权限被赋予的角色
     * @param SysMenuId
     */
    @Override
    public void deleteByMenu(long SysMenuId) {
        SysMenuRoleExample example= new SysMenuRoleExample();
        int sysmenuid=(int)SysMenuId;
        example.createCriteria().andMenuIdEqualTo(sysmenuid);
        List<SysMenuRole> rps= sysMenuRoleMapper.selectByExample(example);
        for (SysMenuRole sysMenuRole : rps)
            sysMenuRoleMapper.deleteByPrimaryKey(sysMenuRole.getId());
    }


    /**
     * 通过MenuId解除Role权限
     * @param menuId
     * @return
     */
    @Override
    public Boolean deleteByMenuId(Integer menuId) {
        SysMenuRoleExample example= new SysMenuRoleExample();
        example.createCriteria().andMenuIdEqualTo(menuId);
        int i=sysMenuRoleMapper.deleteByExample(example);
        if(i>0){
            return true;
        }
        return false;
    }
}
